package com.sc.nft.service.impl;

import com.sc.nft.dao.MallPayOrderItemDao;
import com.sc.nft.entity.MallOrder;
import com.sc.nft.entity.MallPayOrderItem;
import com.sc.nft.service.MallPayOrderItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 小程序商城订单与支付单关联表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallPayOrderItemServiceImpl implements MallPayOrderItemService {

    private final MallPayOrderItemDao mallPayOrderItemDao;

    /**
     * 根据订单ID查询支付单
     *
     * @param orderId
     * @return
     */
    @Override
    public MallPayOrderItem getByOrderId(Long orderId) {
        return mallPayOrderItemDao.getMallPayOrderItemByOrderId(orderId);
    }

    /**
     * 移除关联
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean remove(Long orderId) {
        return mallPayOrderItemDao.removeMallPayOrderItem(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(List<MallPayOrderItem> mallPayOrderItems) {
        // 移除之前的关联关系
        List<Long> orderIds = mallPayOrderItems.stream().map(MallPayOrderItem::getOrderId).collect(Collectors.toList());
        List<MallPayOrderItem> mallPayOrderItemByOrderIds = mallPayOrderItemDao.getMallPayOrderItemByOrderIds(orderIds);
        if (!CollectionUtils.isEmpty(mallPayOrderItemByOrderIds)){
            mallPayOrderItemDao.removeMallPayOrderItem(orderIds);
        }
        // 保存新的关联关系
        return mallPayOrderItemDao.saveBatch(mallPayOrderItems);
    }

    @Override
    public List<MallOrder> getOrderListByPayOrderId(Long payOrderId) {
        return mallPayOrderItemDao.getOrderListByPayOrderId(payOrderId);
    }
}
